---
import BaseLayout from "../layouts/BaseLayout.astro"
---

<BaseLayout childpage backtotop bodyClass="bg-body py-3">
  <div class="container">
    <div class="row g-3">
      <div class="col">
        <form id="form">
          <div class="row mb-3">
            <label for="name" class="col-sm-2 col-form-label text-sm-end"
              >角色名称</label
            >
            <div class="col-sm-10">
              <input type="text" class="form-control" id="name" name="name" />
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script
    is:inline
    slot="script"
    src="https://cdn.jsdelivr.net/gh/ajiho/formvalidation@main/dist/js/formValidation.js"
  ></script>
  <script
    is:inline
    slot="script"
    src="https://cdn.jsdelivr.net/gh/ajiho/formvalidation@main/dist/js/framework/bootstrap.js"
  ></script>
  <script
    is:inline
    slot="script"
    src="https://cdn.jsdelivr.net/gh/ajiho/formvalidation@main/dist/js/language/zh_CN.js"
  ></script>

  <script is:inline slot="js">
    //表单验证
    $("#form")
      .formValidation({
        //验证字段
        fields: {
          name: {
            validators: {
              notEmpty: true,
            },
          },
          //...
        },
      })
      .on("success.form.fv", function (e) {
        //阻止表单提交
        e.preventDefault()
        //得到表单对象
        const $form = $(e.target)
        const data = $form.serialize()

        // 得到序列化数据
        $.ajax({
          url: "/role",
          method: "post",
          data: data,
        }).then((response) => {
          if (response.code === 200) {
            /**
             * 通知父级页面,这里的参数可传递任意参数,如果子页面有多个事件通知父级页面可以传递一个对象来区分
             * 例子：
             * 添加成功
             * {type:'add',data:response}
             * 其它操作
             * {type:'other',data:otherData}
             * 这样在父页面的onMessage回调参数中可以根据type的类型来判断就可以执行不同的逻辑
             */
            window.parent.postMessage(response)
          }
        })
      })
  </script>
</BaseLayout>
